package com.ruoyi.sinatv.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/chatroom/{username}")
public class ChatRoom {

    private static List<Session> userList=new Vector<Session>();

    private static Map<String,Session> userMap = new ConcurrentHashMap<String,Session>();

    @OnOpen
    public void onOpen(Session session,@PathParam("username") String username){
        System.out.println("..............onOpen"+username);

        Map<String, Object> map = session.getUserProperties();
        map.put("username", username);

        userList.add(session);
        userMap.put(username, session);
    }
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {

        Map<String, Object> map = session.getUserProperties();
        String username = (String) map.get("username");

        System.out.println("..............onMessage.........."+username+"........"+message);

        for (Session user : userList) {
            user.getBasicRemote().sendText(username+":"+message);
        }

    }
    @OnClose
    public void onClose(Session session){
        System.out.println("..............onClose");
        userList.remove(session);
    }
    @OnError
    public void onError(Throwable throwable,Session session){
        System.out.println("..............onError");
    }
}
